import React, { useEffect } from "react";
import { Col, Form, Input, InputNumber, DatePicker, Select, Row } from "antd";
import { useTranslation } from 'react-i18next';
import { DROPDOWN, TEXTINPUT, NUMBERINPUT, TEXTAREA, DATEPICKER, ATTACHMENT, ACCEPT_TYPE, DATEFORMAT, DATEFORMAT_HMS, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import { transformArray, resquestDetialAttachmentListFormat } from "../../../utils/commonUtil";
import RequestUploadItem from '../RequestUploadItem';
import _ from 'lodash';
import { apiPermissionApproveSelect } from '../../../services/permissionManager'
import { useState } from "react";
import dayjs from 'dayjs';
import RequestStatus from '../../Components/RequestStatus';


const RequestFormProjectTpl = ({
  listNames,
  form,
  initialValues,
  tplData,
  uploadParams,
  editMode,
  hasApproval,
  projectExtraContentrRender,
  moduleConfig,
}) => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const [assignUserList, setAssignUserList] = useState([]);
  // 不在动态模板中显示
  const projectNotDynamicRenderKey = [
    'approveBy',
    'approveTargetType',
    'buType',
    'createdBy',
    'createdTime',
    'moduleName',
    'requestStatus',
    'templateName',
    'updatedBy',
    'updatedTime',
    'projectName',
    'approvedUser',
    'assign',
    'remark',
    moduleConfig?.detialIdName,
  ];
  const renderData = editMode === RES_MODE.NEW ? { ...initialValues } :
    {
      [listNames]:
      {
        ..._.omit(initialValues?.[listNames], projectNotDynamicRenderKey),
      }
    };
  const { t } = useTranslation();
  const { TextArea } = Input;
  // Project 固定字段
  let projectTplItems = {
    buType: {
      fieldOptionValue: editMode === RES_MODE.NEW ? [tplData.tBu] : initialValues?.[listNames]?.buType?.fieldOptionValue,
      fieldValue: editMode === RES_MODE.NEW ? tplData.tBu : initialValues?.[listNames]?.buType?.fieldValue,
      fieldType: "Text Input",
      isRequired: '1'
    },
    moduleName: {
      fieldOptionValue: editMode === RES_MODE.NEW ? [tplData.tMd] : initialValues?.[listNames]?.moduleName?.fieldOptionValue,
      fieldValue: editMode === RES_MODE.NEW ? tplData.tMd : initialValues?.[listNames]?.moduleName?.fieldValue,
      fieldType: "Text Input",
      isRequired: '1'
    },
    templateName: {
      fieldOptionValue: editMode === RES_MODE.NEW ? [tplData.tTm] : initialValues?.[listNames]?.templateName?.fieldOptionValue,
      fieldValue: editMode === RES_MODE.NEW ? tplData.tTm : initialValues?.[listNames]?.templateName?.fieldValue,
      fieldType: "Text Input",
      isRequired: '1'
    },
    projectName: {
      fieldOptionValue: '',
      fieldValue: editMode === RES_MODE.NEW ? '' : initialValues?.[listNames]?.projectName?.fieldValue,
      fieldType: "Text Input",
      isRequired: '1'
    }
  };
  // 详情固定信息
  if (editMode !== RES_MODE.NEW) {
    ['createdBy', 'createdTime', 'updatedTime', 'requestStatus']?.map((key) => {
      let itemData = initialValues?.[listNames]?.[key];
      itemData.fieldValue = (key === 'createdTime' || key === 'updatedTime') ? dayjs(itemData?.fieldValu).format(DATEFORMAT_HMS) : itemData?.fieldValue;
      projectTplItems[key] = itemData;
    });
    // 已审批的数据, 展示审批人
    (initialValues?.[listNames]?.requestStatus?.fieldValue === APPROVED || initialValues?.[listNames]?.requestStatus?.fieldValue === REJECTED) && ['assign']?.map((key) => {
      projectTplItems[key] = {
        ...initialValues?.[listNames]?.[key],
      }
    });
    // 非new, 需提交, 但界面不显示固定的字段
    [moduleConfig?.detialIdName, 'updatedBy']?.map((key) => {
      projectTplItems[key] = {
        ...initialValues?.[listNames]?.[key],
        isShow: false
      }
    });
    // 审批模式, 显示assign字段
    if ((editMode === RES_MODE.APPROVAL && initialValues?.[listNames]?.requestStatus?.fieldValue === PENDING) ||
      initialValues?.[listNames]?.requestStatus?.fieldValue === APPROVED) {
      projectTplItems['assign'] = {
        fieldOptionValue: [],
        fieldValue: initialValues?.[listNames]?.assign?.fieldValue || '',
        fieldType: "Dropdown",
        isRequired: '1'
      };
    };
    // 测试人员编辑模式
    editMode === RES_MODE.TESTEREDIT && ['assign']?.map((key) => {
      projectTplItems[key] = {
        ...initialValues?.[listNames]?.[key],
        isShow: true
      }
    });
    // 测试人员编辑模式, 增加固定字段
    editMode === RES_MODE.TESTEREDIT && ['remark']?.map((key) => {
      projectTplItems[key] = {
        fieldOptionValue: '',
        fieldValue: initialValues?.[listNames]?.remark?.fieldValue || '',
        fieldType: "TextArea",
        isRequired: '0',
        isShow: false
      }
    });
  };

  const projectTplItemsDisabledStatus = {
    buType: true,
    moduleName: true,
    templateName: true,
    projectName: editMode !== RES_MODE.NEW ? true : false,
    createdBy: true,
    createdTime: true,
    updatedTime: true,
    requestStatus: true,
    // 审批模式, assign字段可编辑
    assign: editMode !== RES_MODE.APPROVAL ? true : false,
    remark: false,
    approveBy: true,
  };
  // console.log(projectTplItems);
  const onChangeDatePicker = (date, dateString) => {
    console.log(date, dateString);
    console.log(new Date(date));
  };
  const apiPermissionApproveSelectAsync = async () => {
    const { data } = await apiPermissionApproveSelect({ buType: initialValues?.[listNames]?.buType?.fieldValue, moduleName: initialValues?.[listNames]?.moduleName?.fieldValue });
    setAssignUserList(data?.data?.item);
  };
  useEffect(() => {
    // 审批模式，获取可assign用户列表
    if ((editMode === RES_MODE.APPROVAL && initialValues?.[listNames]?.requestStatus?.fieldValue === PENDING) ||
      initialValues?.[listNames]?.requestStatus?.fieldValue === APPROVED) {
      apiPermissionApproveSelectAsync();
    };
  }, []);
  useEffect(() => {
    form.setFieldsValue({
      [listNames]: {
        ...renderData?.[listNames],
        ...projectTplItems
      },
    });
  }, [renderData]);
  return (
    <>
      {
        form &&
        <Row gutter={[24, 0]} key='project-row'>
          {
            projectTplItems && Object.keys(projectTplItems)?.map((key) => {
              const itemData = projectTplItems?.[key];
              const labelName = t(`requestDetails.${key}`);
              const itemType = itemData?.fieldType;
              const itemValues = itemData?.fieldValue;
              const optionValues = itemData?.fieldOptionValue;
              const itemRequired = itemData?.isRequired === '1' ? true : false;
              const itemRequiredInt = itemData?.isRequired;
              return (
                <Col span={6} style={{ display: itemData?.isShow === false && 'none' }} key={`project-col-${key}`}>
                  {/* 绑定整个字段内容，用于提交完整数据 */}
                  <Form.Item name={[listNames, key]} style={{ display: 'none' }} key={`project-col-item-${key}`}></Form.Item>
                  <Form.Item
                    key={key}
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 24 }}
                    label={labelName}
                    name={[listNames, key, 'fieldValue']}
                    initialValue={itemValues}
                    rules={[
                      {
                        required: itemRequired,
                        message: t('common.isRequired'),
                      }]}>
                    {
                      key === 'assign' ?
                        <Select disabled={projectTplItemsDisabledStatus?.[key]} options={transformArray(assignUserList)} /> :
                        key === 'requestStatus' ?
                          <RequestStatus status={itemValues} styleProps={{ padding: '5px 12px', fontSize: '14px', width: '100px', }} /> :
                          <Input disabled={projectTplItemsDisabledStatus?.[key]} placeholder={t('common.pleaseEnter')} />
                    }
                  </Form.Item>
                </Col>
              )
            })
          }
          {
            renderData?.[listNames] && Object.keys(renderData?.[listNames])?.map((key) => {
              const itemData = renderData?.[listNames]?.[key];
              const labelName = key;
              const itemType = itemData?.fieldType;
              const optionValues = itemData?.fieldOptionValue;
              const itemValues = itemData?.fieldValue;
              const itemRequired = itemData?.isRequired === '1' ? true : false;
              const itemRequiredInt = itemData?.isRequired;
              const fileList = itemData?.fieldType === ATTACHMENT && resquestDetialAttachmentListFormat(itemData?.fieldValue);
              return (
                <>
                  {itemType === DROPDOWN || itemType === TEXTINPUT || itemType === NUMBERINPUT || itemType === DATEPICKER ?
                    <Col span={6} key={`project-col-${key}`}>
                      {/* 绑定整个字段内容，用于提交完整数据 */}
                      <Form.Item name={[listNames, key]} style={{ display: 'none' }} key={`project-col-item-${key}`}></Form.Item>
                      <Form.Item
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                        label={labelName}
                        key={key}
                        name={[listNames, key, 'fieldValue']}
                        rules={[
                          {
                            required: itemRequired,
                            message: t('common.isRequired'),
                          }]}>
                        {
                          itemType === TEXTINPUT &&
                          <Input placeholder={t('common.pleaseEnter')} />
                        }
                        {
                          itemType === NUMBERINPUT &&
                          <InputNumber placeholder={t('common.pleaseEnter')} style={{ width: '100%' }} />
                        }
                        {
                          itemType === DROPDOWN &&
                          <Select placeholder={t('common.pleaseSelect')} options={transformArray(optionValues)} mode='multiple' />
                        }
                        {
                          itemType === DATEPICKER &&
                          <DatePicker placeholder={t('common.pleaseSelect')} format={DATEFORMAT} onChange={onChangeDatePicker} style={{ width: '100%' }} />
                        }
                      </Form.Item>
                    </Col>
                    :
                    <Col span={24} key={`project-col-${key}`}>
                      {/* 绑定整个字段内容，用于提交完整数据 */}
                      <Form.Item name={[listNames, key]} style={{ display: 'none' }} key={`project-col-item-${key}`}></Form.Item>
                      {/* 单个占一行 */}
                      <Form.Item
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                        label={labelName}
                        key={key}
                        name={[listNames, key, 'fieldValue']}
                        rules={[
                          {
                            required: itemRequired,
                            validator: async (rule, value) => {
                              if (!value && itemRequired) {
                                return Promise.reject(t('common.isRequired'));
                              } else {
                                return Promise.resolve();
                              }
                            }
                          }
                        ]} >
                        {
                          itemType === TEXTAREA &&
                          <TextArea placeholder={t('common.pleaseEnter')} />
                        }
                        {
                          itemType === ATTACHMENT &&
                          <RequestUploadItem
                            btnText={t('common.attachment')}
                            acceptType={ACCEPT_TYPE.ALL}
                            uploadUpdateFn={({ fileList, deleteFileList }) => {
                              const updateProjectData = form?.getFieldsValue()?.[listNames];
                              if (updateProjectData[key]) {
                                updateProjectData[key]['fieldValue'] = fileList;
                                updateProjectData[key]['fieldDeleteValue'] = deleteFileList;
                                form.setFieldsValue({
                                  [listNames]: updateProjectData,
                                });
                                form.validateFields([listNames]);
                              };
                            }}
                            fileListData={fileList}
                          />
                        }
                      </Form.Item>
                    </Col>
                  }
                </>
              )
            })
          }
          {/* project 特殊业务 */}
          {
            initialValues?.project?.requestStatus?.fieldValue === APPROVED &&
            <Col span={24} key={`project-col-result`}>
              <Form.Item
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                label={t('common.remark')}
                name={[listNames, 'remark', 'fieldValue']}>
                <TextArea placeholder={t('common.pleaseEnter')} disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} />
              </Form.Item>
            </Col>
          }
          {
            projectExtraContentrRender &&
            projectExtraContentrRender()
          }
        </Row>
      }
    </>
  )
};

export default RequestFormProjectTpl;